package com.viewsky.base.back.config;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class ServerPropertyConfig implements ApplicationListener<WebServerInitializedEvent>
{	
	private int port;

	@Override
	public void onApplicationEvent(WebServerInitializedEvent event)
	{
		this.port = event.getWebServer().getPort();
	}
	
	public String getServer() 
	{
		String strServer = null;
		Enumeration<NetworkInterface> netInterfaces = null;
		
		try
		{
			netInterfaces = NetworkInterface.getNetworkInterfaces();
			
			while (netInterfaces.hasMoreElements()) 
			{
				NetworkInterface ni = netInterfaces.nextElement();
				Enumeration<InetAddress> ips = ni.getInetAddresses();
				
				while (ips.hasMoreElements()) 
				{
					InetAddress inet = ips.nextElement();
					
					if(!inet.isLoopbackAddress() && inet.isSiteLocalAddress())
					{
						strServer = inet.getHostAddress();
						break;
					}
				}
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
			strServer = e.toString();
		}
		
		return strServer + ":" + this.port;
	}
}
